package net.chasing.androidbaseconfig.util;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import net.chasing.androidbaseconfig.R;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class AppShortCutUtil {
    private static final String TAG = "AppShortCutUtil";
    private static final String APP_NAME = "超级兔子便签";

    /***
     * 在应用图标的快捷方式上加数字
     * @param num 显示的数字：整型
     */
    public static void addNumShortCut(Context context, Class clazz, int num) {
        try {
            if (RomUtils.isXiaomi() || RomUtils.isOppo())
                setNotificationBadge(context, clazz, num);
            else if (RomUtils.isSamsung())
                setSamsungBadge(context, num);
            else if (RomUtils.isVivo())
                setVivoBadge(context, num);
            else if (RomUtils.isHuawei())
                setHuaweiBadge(context, num);
        } catch (Exception ignored) {
        }
    }

    private static String getLauncherClassName(Context context) {
        ComponentName launchComponent = getLauncherComponentName(context);
        if (launchComponent == null) {
            return "";
        } else {
            return launchComponent.getClassName();
        }
    }

    private static ComponentName getLauncherComponentName(Context context) {
        Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(context
                .getPackageName());
        if (launchIntent != null) {
            return launchIntent.getComponent();
        } else {
            return null;
        }
    }

    /***
     * 在vivo应用图标的快捷方式上加数字<br>
     * @param num 显示的数字：大于99，为"99"，当为""时，不显示数字，相当于隐藏了)<br><br>
     * 注意点：
     *
     */
    private static void setVivoBadge(Context context, int num) {
        Log.e(TAG, "vivoShortCut....");
        Intent localIntent = new Intent("launcher.action.CHANGE_APPLICATION_NOTIFICATION_NUM");
        localIntent.putExtra("packageName", context.getPackageName());
        String launchClassName = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()).getComponent().getClassName();
        localIntent.putExtra("className", launchClassName);
        if (num > 99) {
            num = 99;
        }
        localIntent.putExtra("notificationNum", num);
//        intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
        context.sendBroadcast(localIntent);
    }

    /***
     * 在华为应用图标的快捷方式上加数字<br>
     *
     * @param num 显示的数字：大于99，为"99"，当为""时，不显示数字，相当于隐藏了)<br><br>
     *
     * 注意点：
     * context.getPackageName()+"/."+clazz.getSimpleName() （这个是启动activity的路径）中的"/."不能缺少
     */
    private static boolean setHuaweiBadge(Context context, int num) {
        try {
            String launchClassName = getLauncherClassName(context);
            if (TextUtils.isEmpty(launchClassName)) {
                return false;
            }
            Bundle bundle = new Bundle();
            bundle.putString("package", context.getPackageName());
            bundle.putString("class", launchClassName);
            bundle.putInt("badgenumber", num);
            context.getContentResolver().call(Uri.parse("content://com.huawei.android.launcher" +
                    ".settings/badge/"), "change_badge", null, bundle);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /***
     * 三星手机：应用图标的快捷方式上加数字
     */
    private static boolean setSamsungBadge(Context context, int num) {
        try {
            String launcherClassName = getLauncherClassName(context);
            if (TextUtils.isEmpty(launcherClassName)) {
                return false;
            }
            Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
            intent.putExtra("badge_count", num);
            intent.putExtra("badge_count_package_name", context.getPackageName());
            intent.putExtra("badge_count_class_name", launcherClassName);
            context.sendBroadcast(intent);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static int notificationId = 1000;

    //xiaomi oppo 通用
    public static void setNotificationBadge(Context context, Class clazz, int count) {
        if (count == 0) return;
        NotificationManager notificationManager = (NotificationManager) context.getSystemService
                (Context.NOTIFICATION_SERVICE);
        if (notificationManager == null) {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 8.0之后添加角标需要NotificationChannel
            NotificationChannel channel = new NotificationChannel("badge", "通知角标",
                    NotificationManager.IMPORTANCE_DEFAULT);
            channel.setShowBadge(true);
            channel.enableLights(false);
            channel.enableVibration(false);
            channel.setSound(null, null);
            notificationManager.createNotificationChannel(channel);
        }

        String content = "您有" + count + "条今日待办";
        Intent intent = new Intent(context, clazz);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE);
        Notification notification = new NotificationCompat.Builder(context, "badge")
                .setContentTitle(APP_NAME)
                .setContentText(content)
                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.logo))
                .setSmallIcon(R.mipmap.logo)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .setChannelId("badge")
                .setNumber(count)
                .setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL).build();

        // 小米
        try {
            Field field = notification.getClass().getDeclaredField("extraNotification");
            Object extraNotification = field.get(notification);
            Method method = extraNotification.getClass().getDeclaredMethod("setMessageCount", int.class);
            method.invoke(extraNotification, count);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //id不能一样，否则会显示不出角标
        notificationManager.notify(notificationId, notification);
    }
}
